<?php
namespace Admin\Controller;
use \Think\Controller;
//此控制器处理登陆相关
class LoginController extends Controller{
    //执行登陆
    
     public function index()
    {
        $this->display('Login/index');
    }

    public function vcode()
    {
        $Verify = new \Think\Verify();
        $Verify->length = 4;
        $Verify->entry();
    }



    public function login()
    {
        foreach ($_POST as $val) {
            if (empty($val)) {
                $this->error('请完善数据',U('Login/index'),1);
                exit;
            }
        }
        $vcode = I('post.vcode');
        if (!check_verify($vcode)) {
            $this->error('验证码错误',U('Login/index'),1);
            exit;
        }
        // 用户密码验证
        $password = md5(I('post.pass'));
        //拿到POST里面的用户名和密码
        $data['username'] = I('post.name');
        $user = D('admin');
        //用用户名进数据库进行查询
        $u = $user->where($data)->find();
        if (!$u) {
            $this->error('用户名不存在',U('Login/index'),1);
        } elseif ($password != $u['pass']) {
            $this->error('密码错误',U('Login/index'),1);
        } elseif ($u['denied'] == 0) {
            $this->error('您的账号已被禁用',U('Login/index'));
        } else {
            $nodelist = array();
            if ($u['username'] != 'admin') {
            
            //如果不是admin.则查询节点
            $list = M('node')->field('mname,aname')->where('id in'.M('role_node')->field('nid')->where("rid in ".M('user_role')->field('rid')->where(array('uid'=>array('eq',$u['id'])))->buildSql())->buildSql())->select();
            // var_dump($list);exit;
        //控制器名转换为大写
        foreach ($list as $key => $val) {
            $list[$key]['mname'] = ucfirst($val['mname']);
        }

        //查看查询出来的信息
        

        $nodelist = array();
        $nodelist['Index'] = array('index');
        //遍历重新拼装
        foreach($list as $v){
            $nodelist[$v['mname']][] = $v['aname'];
            //把修改和执行修改 添加和执行添加 拼装到一起
            if($v['aname']=="edit"){
                $nodelist[$v['mname']][]="save";
            }
            if($v['aname']=="add"){
                $nodelist[$v['mname']][]="insert";
            }
        }
       // var_dump($nodelist);exit;
            
        }  //if结束

            //正确,写入session
            $admin_user['nodelist'] = $nodelist;
            $admin_user['id'] = $u['id'];
            $admin_user['name'] = $u['name'];
            $admin_user['username'] = $u['username'];
            $admin_user['image'] = $u['image'];
            session('verify_code', null);
            session('verify_time', null);
            session('admin_user',$admin_user);
            // print_r($_SESSION);exit;
            $this->redirect('Index/index');
        }  //else结束
    }

    public function logout()
    {
        session('admin_user', null);
        $this->redirect('Login/index');
    }
}